import axios from "axios";
import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Button, Input, Form, Notify } from "react-vant";
import { useAppDispatch } from "../../app/hooks";
import { loginSuccess } from "../../app/user/userSlice";

export default () => {
  const [form] = Form.useForm();
  const [count, setCount] = useState(60);
	const navigate = useNavigate()
	const dispatch = useAppDispatch()
  const onFinish = (values: any) => {
    axios.post("/api/tel/login", values).then((resp) => {
			const { code, data, message } = resp.data;
			if(code === 200) {
				// 存储数据
				dispatch(loginSuccess(data));
				navigate('/my')
			}
    });
  };

  const getCode = () => {
    const tel = form.getFieldValue("tel");
    // 验证手机号
    if (!/^1[3-8]\d{9}$/.test(tel)) {
      Notify.show({ type: "danger", message: "手机号格式不正确" });
      return;
    }

    // 发送请求
    axios.get("/api/tel", { params: { tel } }).then((resp) => {
      console.log(resp.data);
      const { code, message, data } = resp.data;
      if (code === 200) {
        // 倒计时
        setCount((state) => state - 1);
        const timer = setInterval(() => {
          setCount((state) => {
            if (state <= 1) {
              clearInterval(timer);
              return 60;
            }

            return state - 1;
          });
        }, 1000);
      }
    });
  };

  return (
    <div>
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div style={{ margin: "16px 16px 0" }}>
            <Button round nativeType="submit" type="primary" block>
              登录
            </Button>
          </div>
        }
      >
        <Form.Item
          rules={[
            { required: true, message: "请填写手机号" },
            { pattern: /^1[3-8]\d{9}$/, message: "请输入正确的手机号" },
          ]}
          name="tel"
          label="手机号"
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>
        <Form.Item
          rules={[{ required: true, message: "请填写验证码" }]}
          name="code"
          label="验证码"
        >
          <Input
            placeholder="请输入密码"
            suffix={
              <Button
                disabled={count !== 60}
                size="small"
                type="primary"
                onClick={() => getCode()}
              >
                {count === 60 ? "获取验证码" : "还剩" + count + "s"}
              </Button>
            }
          />
        </Form.Item>
      </Form>
    </div>
  );
};
